#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
from typing import List, Dict
from .base import FilterRule

class FileExtensionFilter(FilterRule):
    """文件扩展名过滤规则 - 只保留.md文件"""
    
    def __init__(self, allowed_extensions: List[str] = None):
        """
        初始化文件扩展名过滤器
        
        Args:
            allowed_extensions: 允许的文件扩展名列表，默认为['.md']
        """
        if allowed_extensions is None:
            allowed_extensions = ['.md']
        self.allowed_extensions = allowed_extensions
    
    def should_filter(self, add_content: str, remove_content: str, hunk_changes: List[Dict]) -> bool:
        """判断是否应该过滤（非.md文件）"""
        # 从hunk_changes中获取文件路径信息
        if not hunk_changes:
            return False  # 如果没有hunk_changes信息，不过滤
        
        # 扫描所有 hunk 的 file_path；若任一允许，则不过滤
        allowed_exts = [ext.lower() for ext in self.allowed_extensions]
        file_paths = []
        for hunk in hunk_changes:
            if isinstance(hunk, dict) and 'file_path' in hunk:
                file_paths.append(hunk['file_path'])
        
        if not file_paths:
            return False
        
        for fp in file_paths:
            _, ext = os.path.splitext(fp)
            if ext.lower() in allowed_exts:
                return False
        
        return True
    
    def get_filter_reason(self) -> str:
        """获取过滤原因"""
        return f"file_extension_not_allowed: {self.allowed_extensions}" 